package com.zhanggm.starter.uploader.service;

import com.zhanggm.common.utils.FileUtil;
import com.zhanggm.starter.uploader.FileProperties;
import com.zhanggm.starter.uploader.common.FileResult;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 文件上传的服务类（批量上传）
 */
public class FileService {

    private FileProperties fileProperties;

    public FileService(FileProperties properties) {
        this.fileProperties = properties;
    }

    /**
     * List<FileResult> 多个图片上传结果
     * @param files
     * @return
     */
    public List<FileResult> upload(MultipartFile[] files){
        //文件上传信息
        List<FileResult> fileList = new ArrayList<>();
        //循环保存文件
        for (MultipartFile file : files){
            //生成文件名
            String originalFilename = file.getOriginalFilename();
            //小一工具类工程
            String extName = FileUtil.getExtName(originalFilename);
            String fileName = UUID.randomUUID()+extName;
            //保存文件
            File saveFile = new File(fileProperties.getPath(),fileName);
            try {
                file.transferTo(saveFile);
                //添加到文件上传信息到list
                FileResult fileResult = new FileResult(fileName, fileProperties.getDomain()+fileName);
                fileList.add(fileResult);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return fileList;
    }
}
